<template>
  <div class="user-segmentation">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>用户分群分析</h2>
        <p>基于用户行为和特征的智能分群，精准识别不同价值用户群体</p>
      </div>
      <div class="header-actions">
        <el-button :icon="Setting" @click="showSegmentationConfig = true">
          分群配置
        </el-button>
        <el-button :icon="Refresh" @click="refreshData" :loading="loading">刷新</el-button>
        <el-button type="primary" :icon="Plus" @click="createNewSegmentation">
          新建分群
        </el-button>
      </div>
    </div>

    <!-- 分群概览 -->
    <div class="segmentation-overview" v-loading="loading">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="6" v-for="overview in segmentationOverview" :key="overview.key">
          <el-card class="overview-card" :class="overview.key">
            <div class="overview-content">
              <div class="overview-icon">
                <el-icon :size="28" :color="overview.color">
                  <component :is="overview.icon" />
                </el-icon>
              </div>
              <div class="overview-info">
                <h3>{{ overview.title }}</h3>
                <p class="overview-value">{{ overview.value }}</p>
                <span class="overview-desc">{{ overview.description }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分群方法选择 -->
    <div class="segmentation-methods">
      <el-card>
        <template #header>
          <h3>分群方法</h3>
        </template>
        <div class="methods-grid">
          <div
            class="method-item"
            v-for="method in segmentationMethods"
            :key="method.key"
            :class="{ active: selectedMethod === method.key }"
            @click="selectMethod(method.key)"
          >
            <div class="method-icon">
              <el-icon :size="32" :color="method.color">
                <component :is="method.icon" />
              </el-icon>
            </div>
            <div class="method-content">
              <h4>{{ method.name }}</h4>
              <p>{{ method.description }}</p>
              <div class="method-features">
                <el-tag v-for="feature in method.features" :key="feature" size="small" type="info">
                  {{ feature }}
                </el-tag>
              </div>
            </div>
            <div class="method-status">
              <el-tag :type="method.status === 'active' ? 'success' : 'info'" size="small">
                {{ method.status === 'active' ? '已启用' : '未启用' }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分群结果展示 -->
    <div class="segmentation-results" v-if="selectedMethod">
      <el-card>
        <template #header>
          <div class="results-header">
            <h3>{{ getMethodName(selectedMethod) }}分群结果</h3>
            <div class="results-controls">
              <el-select v-model="resultView" size="small" style="width: 120px">
                <el-option label="卡片视图" value="card" />
                <el-option label="表格视图" value="table" />
                <el-option label="图表视图" value="chart" />
              </el-select>
              <el-button size="small" :icon="Download" @click="exportSegmentation">
                导出结果
              </el-button>
            </div>
          </div>
        </template>

        <!-- 卡片视图 -->
        <div v-if="resultView === 'card'" class="card-view">
          <div class="segments-grid">
            <div
              class="segment-card"
              v-for="segment in currentSegments"
              :key="segment.id"
              @click="viewSegmentDetail(segment)"
            >
              <div class="segment-header">
                <h4>{{ segment.name }}</h4>
                <el-tag :type="segment.type" size="small">{{ segment.level }}</el-tag>
              </div>
              <div class="segment-metrics">
                <div class="metric-item">
                  <span class="metric-label">用户数量</span>
                  <span class="metric-value">{{ segment.userCount.toLocaleString() }}</span>
                </div>
                <div class="metric-item">
                  <span class="metric-label">占比</span>
                  <span class="metric-value">{{ segment.percentage }}%</span>
                </div>
                <div class="metric-item">
                  <span class="metric-label">平均价值</span>
                  <span class="metric-value">¥{{ segment.avgValue }}</span>
                </div>
              </div>
              <div class="segment-description">
                {{ segment.description }}
              </div>
              <div class="segment-actions">
                <el-button size="small" type="primary" link>
                  查看详情
                </el-button>
                <el-button size="small" type="info" link>
                  营销策略
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 表格视图 -->
        <div v-if="resultView === 'table'" class="table-view">
          <el-table :data="currentSegments" stripe>
            <el-table-column prop="name" label="分群名称" width="150" />
            <el-table-column prop="userCount" label="用户数量" width="120">
              <template #default="{ row }">
                {{ row.userCount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="percentage" label="占比" width="100">
              <template #default="{ row }">
                {{ row.percentage }}%
              </template>
            </el-table-column>
            <el-table-column prop="avgValue" label="平均价值" width="120">
              <template #default="{ row }">
                ¥{{ row.avgValue }}
              </template>
            </el-table-column>
            <el-table-column prop="level" label="价值等级" width="120">
              <template #default="{ row }">
                <el-tag :type="row.type" size="small">{{ row.level }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="特征描述" min-width="200" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="primary" link @click="viewSegmentDetail(row)">
                  查看详情
                </el-button>
                <el-button size="small" type="info" link @click="createStrategy(row)">
                  营销策略
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 图表视图 -->
        <div v-if="resultView === 'chart'" class="chart-view">
          <el-row :gutter="20">
            <el-col :xs="24" :lg="12">
              <div class="chart-container">
                <h4>用户分群分布</h4>
                <PieChartComponent
                  :data="segmentDistributionData"
                  height="300px"
                  :radius="['40%', '70%']"
                  @chart-click="handleSegmentChartClick"
                />
              </div>
            </el-col>
            <el-col :xs="24" :lg="12">
              <div class="chart-container">
                <h4>分群价值对比</h4>
                <BaseChart
                  :option="segmentValueOption"
                  height="300px"
                  @chart-click="handleValueChartClick"
                />
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

    <!-- 分群配置对话框 -->
    <el-dialog
      v-model="showSegmentationConfig"
      title="分群配置"
      width="600px"
    >
      <el-form :model="configForm" label-width="120px">
        <el-form-item label="分群方法">
          <el-select v-model="configForm.method" style="width: 100%">
            <el-option label="RFM分析" value="rfm" />
            <el-option label="K-means聚类" value="kmeans" />
            <el-option label="行为分群" value="behavior" />
            <el-option label="价值分群" value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="分群数量">
          <el-input-number v-model="configForm.clusterCount" :min="2" :max="10" style="width: 100%" />
        </el-form-item>
        <el-form-item label="特征权重">
          <div class="weight-config">
            <div class="weight-item">
              <span>消费金额</span>
              <el-slider v-model="configForm.weights.amount" :max="100" />
            </div>
            <div class="weight-item">
              <span>消费频次</span>
              <el-slider v-model="configForm.weights.frequency" :max="100" />
            </div>
            <div class="weight-item">
              <span>最近消费</span>
              <el-slider v-model="configForm.weights.recency" :max="100" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="更新频率">
          <el-select v-model="configForm.updateFrequency" style="width: 100%">
            <el-option label="每日" value="daily" />
            <el-option label="每周" value="weekly" />
            <el-option label="每月" value="monthly" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSegmentationConfig = false">取消</el-button>
          <el-button type="primary" @click="saveConfig">保存配置</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分群详情对话框 -->
    <el-dialog
      v-model="showSegmentDetail"
      :title="`${currentSegment?.name} - 详细信息`"
      width="800px"
    >
      <div class="segment-detail" v-if="currentSegment">
        <el-tabs v-model="detailActiveTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="分群名称">{{ currentSegment.name }}</el-descriptions-item>
              <el-descriptions-item label="价值等级">
                <el-tag :type="currentSegment.type" size="small">{{ currentSegment.level }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="用户数量">{{ currentSegment.userCount.toLocaleString() }}</el-descriptions-item>
              <el-descriptions-item label="占比">{{ currentSegment.percentage }}%</el-descriptions-item>
              <el-descriptions-item label="平均价值">¥{{ currentSegment.avgValue }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ currentSegment.createTime }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="用户特征" name="features">
            <div class="feature-analysis">
              <div class="feature-item" v-for="feature in currentSegment.features" :key="feature.name">
                <div class="feature-header">
                  <span class="feature-name">{{ feature.name }}</span>
                  <span class="feature-value">{{ feature.value }}</span>
                </div>
                <el-progress :percentage="feature.score" :stroke-width="8" />
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="营销建议" name="strategy">
            <div class="strategy-content">
              <div class="strategy-item" v-for="strategy in currentSegment.strategies" :key="strategy.type">
                <h5>{{ strategy.title }}</h5>
                <p>{{ strategy.description }}</p>
                <div class="strategy-actions">
                  <el-tag v-for="action in strategy.actions" :key="action" size="small" type="info">
                    {{ action }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Setting, Refresh, Plus, Download,
  DataBoard, User, TrendCharts, Grid
} from '@element-plus/icons-vue'
import { BaseChart, PieChart as PieChartComponent } from '@/components/charts'
import { getUserSegmentationAnalysis } from '@/api/analysis'

// 响应式数据
const loading = ref(false)
const selectedMethod = ref('rfm')
const resultView = ref('card')
const showSegmentationConfig = ref(false)
const showSegmentDetail = ref(false)
const currentSegment = ref(null)
const detailActiveTab = ref('basic')

// API数据存储
const apiData = ref({
  segment_distribution: [],
  segment_details: {},
  rfm_heatmap: [],
  summary: {
    total_segments: 0,
    covered_users: 0,
    high_value_ratio: 0,
    segmentation_accuracy: 0
  }
})

// 配置表单
const configForm = ref({
  method: 'rfm',
  clusterCount: 6,
  weights: {
    amount: 40,
    frequency: 30,
    recency: 30
  },
  updateFrequency: 'weekly'
})

// 分群概览数据（基于API数据计算）
const segmentationOverview = computed(() => {
  const summary = apiData.value.summary

  return [
    {
      key: 'total_segments',
      title: '分群数量',
      value: summary.total_segments ? summary.total_segments.toString() : '6',
      description: '当前活跃分群',
      icon: 'Grid',
      color: '#409EFF'
    },
    {
      key: 'covered_users',
      title: '覆盖用户',
      value: summary.covered_users ? summary.covered_users.toLocaleString() : '156,789',
      description: '已分群用户数',
      icon: 'User',
      color: '#67C23A'
    },
    {
      key: 'high_value_ratio',
      title: '高价值用户占比',
      value: summary.high_value_ratio ? `${summary.high_value_ratio}%` : '32.5%',
      description: '高价值用户比例',
      icon: 'TrendCharts',
      color: '#E6A23C'
    },
    {
      key: 'segmentation_accuracy',
      title: '分群准确度',
      value: summary.segmentation_accuracy ? `${summary.segmentation_accuracy}%` : '89.2%',
      description: '模型准确度',
      icon: 'DataBoard',
      color: '#F56C6C'
    }
  ]
})

// 分群方法数据
const segmentationMethods = ref([
  {
    key: 'rfm',
    name: 'RFM分析',
    description: '基于消费频率、金额和最近消费时间的经典分群方法',
    features: ['消费频率', '消费金额', '最近消费'],
    status: 'active',
    icon: 'TrendCharts',
    color: '#409EFF'
  },
  {
    key: 'kmeans',
    name: 'K-means聚类',
    description: '基于机器学习的无监督聚类算法',
    features: ['多维特征', '自动聚类', '智能分群'],
    status: 'inactive',
    icon: 'DataBoard',
    color: '#67C23A'
  },
  {
    key: 'behavior',
    name: '行为分群',
    description: '基于用户行为模式的分群方法',
    features: ['行为路径', '活跃度', '偏好分析'],
    status: 'inactive',
    icon: 'User',
    color: '#E6A23C'
  },
  {
    key: 'value',
    name: '价值分群',
    description: '基于用户生命周期价值的分群方法',
    features: ['CLV计算', '价值预测', '潜力挖掘'],
    status: 'inactive',
    icon: 'Grid',
    color: '#F56C6C'
  }
])

// RFM分群数据（基于API数据生成）
const rfmSegments = computed(() => {
  if (apiData.value.segment_distribution.length > 0) {
    return apiData.value.segment_distribution.map((segment, index) => {
      const segmentDetail = apiData.value.segment_details[segment.label] || {}

      return {
        id: index + 1,
        name: segment.label,
        level: getSegmentLevel(segment.label),
        type: getSegmentType(segment.label),
        userCount: segment.value,
        percentage: segment.percentage || 0,
        avgValue: Math.round(segmentDetail.avg_monetary || 0),
        description: getSegmentDescription(segment.label),
        createTime: '2024-01-01',
        features: generateSegmentFeatures(segment.label, segmentDetail),
        strategies: getSegmentStrategies(segment.label)
      }
    })
  }

  // 后备数据
  return [
  {
    id: 1,
    name: '重要价值客户',
    level: '高价值',
    type: 'success',
    userCount: 8650,
    percentage: 18.9,
    avgValue: 2850,
    description: '最近购买时间近、购买频率高、消费金额大的用户',
    createTime: '2024-01-01',
    features: [
      { name: '消费频率', value: '高', score: 85 },
      { name: '消费金额', value: '高', score: 90 },
      { name: '最近消费', value: '近', score: 88 }
    ],
    strategies: [
      {
        type: 'retention',
        title: '客户保持策略',
        description: '提供VIP服务，个性化推荐，优先客服支持',
        actions: ['VIP专享', '个性推荐', '专属客服']
      },
      {
        type: 'upsell',
        title: '价值提升策略',
        description: '推荐高价值产品，交叉销售相关商品',
        actions: ['高端产品', '套餐推荐', '会员升级']
      }
    ]
  },
  {
    id: 2,
    name: '重要保持客户',
    level: '高价值',
    type: 'success',
    userCount: 6200,
    percentage: 13.6,
    avgValue: 2150,
    description: '购买频率高、消费金额大，但最近购买时间较远',
    createTime: '2024-01-01',
    features: [
      { name: '消费频率', value: '高', score: 82 },
      { name: '消费金额', value: '高', score: 85 },
      { name: '最近消费', value: '远', score: 45 }
    ],
    strategies: [
      {
        type: 'winback',
        title: '客户召回策略',
        description: '发送个性化优惠券，推送新品信息',
        actions: ['优惠券', '新品推送', '活动邀请']
      }
    ]
  },
  {
    id: 3,
    name: '重要发展客户',
    level: '中价值',
    type: 'warning',
    userCount: 12800,
    percentage: 28.0,
    avgValue: 1680,
    description: '最近购买时间近、消费金额大，但购买频率不高',
    createTime: '2024-01-01',
    features: [
      { name: '消费频率', value: '低', score: 35 },
      { name: '消费金额', value: '高', score: 80 },
      { name: '最近消费', value: '近', score: 85 }
    ],
    strategies: [
      {
        type: 'development',
        title: '客户发展策略',
        description: '增加购买频率，培养购买习惯',
        actions: ['频次激励', '习惯培养', '定期提醒']
      }
    ]
  },
  {
    id: 4,
    name: '重要挽留客户',
    level: '中价值',
    type: 'warning',
    userCount: 9500,
    percentage: 20.8,
    avgValue: 1450,
    description: '购买频率高、消费金额大，但最近购买时间很远',
    createTime: '2024-01-01',
    features: [
      { name: '消费频率', value: '高', score: 78 },
      { name: '消费金额', value: '高', score: 75 },
      { name: '最近消费', value: '很远', score: 25 }
    ],
    strategies: [
      {
        type: 'retention',
        title: '客户挽留策略',
        description: '重点关注，提供特别优惠和关怀',
        actions: ['特别优惠', '客户关怀', '问题解决']
      }
    ]
  },
  {
    id: 5,
    name: '一般价值客户',
    level: '低价值',
    type: 'info',
    userCount: 5800,
    percentage: 12.7,
    avgValue: 680,
    description: '各项指标都处于中等水平的用户',
    createTime: '2024-01-01',
    features: [
      { name: '消费频率', value: '中', score: 50 },
      { name: '消费金额', value: '中', score: 55 },
      { name: '最近消费', value: '中', score: 52 }
    ],
    strategies: [
      {
        type: 'nurture',
        title: '客户培育策略',
        description: '逐步提升用户价值和活跃度',
        actions: ['价值提升', '活跃促进', '体验优化']
      }
    ]
  },
  {
    id: 6,
    name: '流失客户',
    level: '低价值',
    type: 'danger',
    userCount: 2728,
    percentage: 6.0,
    avgValue: 320,
    description: '很久没有购买，购买频率和金额都很低',
    createTime: '2024-01-01',
    features: [
      { name: '消费频率', value: '低', score: 20 },
      { name: '消费金额', value: '低', score: 25 },
      { name: '最近消费', value: '很远', score: 15 }
    ],
    strategies: [
      {
        type: 'winback',
        title: '客户召回策略',
        description: '大力度优惠，重新激活用户',
        actions: ['大额优惠', '新用户待遇', '产品体验']
      }
    ]
  }
  ]
})

// 辅助函数
const getSegmentLevel = (segmentName) => {
  const highValueSegments = ['冠军客户', '忠诚客户', '重要价值客户', '重要保持客户']
  const midValueSegments = ['潜力客户', '新客户', '重要发展客户', '需要关注客户']

  if (highValueSegments.includes(segmentName)) return '高价值'
  if (midValueSegments.includes(segmentName)) return '中价值'
  return '低价值'
}

const getSegmentType = (segmentName) => {
  const successSegments = ['冠军客户', '忠诚客户', '重要价值客户', '重要保持客户']
  const warningSegments = ['潜力客户', '新客户', '重要发展客户', '有风险客户', '需要关注客户']

  if (successSegments.includes(segmentName)) return 'success'
  if (warningSegments.includes(segmentName)) return 'warning'
  return 'danger'
}

const getSegmentDescription = (segmentName) => {
  const descriptions = {
    '冠军客户': '最近购买时间近、购买频率高、消费金额大的顶级用户',
    '忠诚客户': '购买频率高、消费金额大的忠实用户',
    '潜力客户': '有潜力成为高价值用户的客户群体',
    '新客户': '新注册或首次购买的用户',
    '有风险客户': '消费能力强但活跃度下降的用户',
    '需要关注客户': '需要特别关注和维护的用户',
    '即将流失客户': '有流失风险的用户群体',
    '流失客户': '已经流失或长期不活跃的用户',
    '重要价值客户': '最近购买时间近、购买频率高、消费金额大的用户',
    '重要保持客户': '购买频率高、消费金额大，但最近购买时间较远',
    '重要发展客户': '最近购买时间近、消费金额大，但购买频率不高',
    '重要挽留客户': '购买频率高、消费金额大，但最近购买时间很远',
    '一般价值客户': '各项指标都处于中等水平的用户'
  }
  return descriptions[segmentName] || '用户分群描述'
}

const generateSegmentFeatures = (segmentName, segmentDetail) => {
  // 基于分群名称和详细数据生成特征评分
  const getScoreBySegment = (segmentName, featureType) => {
    const scoreMap = {
      '冠军客户': { frequency: 95, monetary: 95, recency: 95 },
      '忠诚客户': { frequency: 85, monetary: 85, recency: 80 },
      '潜力客户': { frequency: 60, monetary: 75, recency: 85 },
      '新客户': { frequency: 30, monetary: 50, recency: 90 },
      '有风险客户': { frequency: 80, monetary: 80, recency: 40 },
      '需要关注客户': { frequency: 50, monetary: 60, recency: 60 },
      '即将流失客户': { frequency: 40, monetary: 40, recency: 25 },
      '流失客户': { frequency: 20, monetary: 30, recency: 15 },
      '重要价值客户': { frequency: 85, monetary: 90, recency: 88 },
      '重要保持客户': { frequency: 85, monetary: 85, recency: 70 },
      '重要发展客户': { frequency: 60, monetary: 85, recency: 85 },
      '重要挽留客户': { frequency: 80, monetary: 80, recency: 40 },
      '一般价值客户': { frequency: 50, monetary: 50, recency: 50 }
    }
    return scoreMap[segmentName]?.[featureType] || 50
  }

  return [
    {
      name: '消费频率',
      value: getScoreBySegment(segmentName, 'frequency') > 70 ? '高' :
             getScoreBySegment(segmentName, 'frequency') > 40 ? '中' : '低',
      score: getScoreBySegment(segmentName, 'frequency')
    },
    {
      name: '消费金额',
      value: getScoreBySegment(segmentName, 'monetary') > 70 ? '高' :
             getScoreBySegment(segmentName, 'monetary') > 40 ? '中' : '低',
      score: getScoreBySegment(segmentName, 'monetary')
    },
    {
      name: '最近消费',
      value: getScoreBySegment(segmentName, 'recency') > 70 ? '近' :
             getScoreBySegment(segmentName, 'recency') > 40 ? '中' : '远',
      score: getScoreBySegment(segmentName, 'recency')
    }
  ]
}

const getSegmentStrategies = (segmentName) => {
  const strategiesMap = {
    '冠军客户': [
      {
        type: 'retention',
        title: '客户保持策略',
        description: '提供VIP服务，个性化推荐，优先客服支持',
        actions: ['VIP专享', '个性推荐', '专属客服']
      },
      {
        type: 'upsell',
        title: '价值提升策略',
        description: '推荐高价值产品，交叉销售相关商品',
        actions: ['高端产品', '套餐推荐', '会员升级']
      }
    ],
    '忠诚客户': [
      {
        type: 'retention',
        title: '忠诚度维护',
        description: '保持客户忠诚度，提供持续价值',
        actions: ['会员权益', '专属活动', '积分奖励']
      }
    ],
    '潜力客户': [
      {
        type: 'development',
        title: '潜力开发策略',
        description: '引导客户增加购买频率和金额',
        actions: ['产品推荐', '优惠激励', '使用指导']
      }
    ],
    '新客户': [
      {
        type: 'onboarding',
        title: '新客户引导',
        description: '帮助新客户快速了解产品和服务',
        actions: ['新手指南', '首购优惠', '客服引导']
      }
    ],
    '有风险客户': [
      {
        type: 'retention',
        title: '风险预警策略',
        description: '及时干预，防止客户流失',
        actions: ['关怀回访', '专属优惠', '问题解决']
      }
    ],
    '需要关注客户': [
      {
        type: 'attention',
        title: '重点关注策略',
        description: '加强沟通，了解客户需求',
        actions: ['定期回访', '需求调研', '服务改进']
      }
    ],
    '即将流失客户': [
      {
        type: 'winback',
        title: '流失预防策略',
        description: '紧急挽回措施，防止客户流失',
        actions: ['大额优惠', '专人服务', '问题解决']
      }
    ],
    '流失客户': [
      {
        type: 'winback',
        title: '客户召回策略',
        description: '大力度优惠，重新激活用户',
        actions: ['大额优惠', '新用户待遇', '产品体验']
      }
    ],
    '重要价值客户': [
      {
        type: 'retention',
        title: '客户保持策略',
        description: '提供VIP服务，个性化推荐，优先客服支持',
        actions: ['VIP专享', '个性推荐', '专属客服']
      }
    ],
    '重要保持客户': [
      {
        type: 'retention',
        title: '客户保持策略',
        description: '维护高价值客户关系，防止流失',
        actions: ['专属服务', '定期回访', '优惠活动']
      }
    ],
    '重要发展客户': [
      {
        type: 'development',
        title: '客户发展策略',
        description: '提升客户购买频率和忠诚度',
        actions: ['频次激励', '会员升级', '交叉销售']
      }
    ],
    '重要挽留客户': [
      {
        type: 'winback',
        title: '客户挽留策略',
        description: '重新激活高价值但不活跃的客户',
        actions: ['回归优惠', '专人服务', '需求调研']
      }
    ],
    '一般价值客户': [
      {
        type: 'general',
        title: '通用策略',
        description: '提供标准化服务，寻找提升机会',
        actions: ['标准服务', '促销活动', '产品推荐']
      }
    ]
  }

  return strategiesMap[segmentName] || [
    {
      type: 'general',
      title: '通用策略',
      description: '根据用户特征制定个性化策略',
      actions: ['个性化服务', '定期沟通', '价值提升']
    }
  ]
}

// 计算属性
const currentSegments = computed(() => {
  switch (selectedMethod.value) {
    case 'rfm':
      return rfmSegments.value
    default:
      return rfmSegments.value
  }
})

const segmentDistributionData = computed(() => {
  return currentSegments.value.map(segment => ({
    name: segment.name,
    value: segment.userCount
  }))
})

const segmentValueOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: ¥{c}'
    },
    xAxis: {
      type: 'category',
      data: currentSegments.value.map(segment => segment.name),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '平均价值(元)'
    },
    series: [{
      type: 'bar',
      data: currentSegments.value.map(segment => segment.avgValue),
      itemStyle: {
        color: (params) => {
          const colors = ['#67C23A', '#67C23A', '#E6A23C', '#E6A23C', '#909399', '#F56C6C']
          return colors[params.dataIndex] || '#409EFF'
        }
      }
    }]
  }
})

// 加载用户分群分析数据
const loadSegmentationData = async () => {
  try {
    loading.value = true
    // 传递分群方法参数
    const response = await getUserSegmentationAnalysis({ method: selectedMethod.value })

    if (response.success) {
      apiData.value = response.data
      ElMessage.success(`${getMethodName(selectedMethod.value)}数据加载成功`)
    } else {
      ElMessage.error(response.message || '获取分群分析数据失败')
      // 使用模拟数据作为后备
      loadMockData()
    }
  } catch (error) {
    console.error('获取分群分析数据失败:', error)
    ElMessage.error('获取分群分析数据失败，使用模拟数据')
    // 使用模拟数据作为后备
    loadMockData()
  } finally {
    loading.value = false
  }
}

// 获取分群方法名称
const getMethodName = (method) => {
  const methodNames = {
    'rfm': 'RFM分群',
    'kmeans': 'K-means聚类',
    'behavior': '行为分群',
    'value': '价值分群'
  }
  return methodNames[method] || '分群'
}

// 加载模拟数据
const loadMockData = () => {
  apiData.value = {
    segment_distribution: [
      { label: '冠军客户', value: 8650, percentage: 18.9 },
      { label: '忠诚客户', value: 6200, percentage: 13.6 },
      { label: '潜力客户', value: 12800, percentage: 28.0 },
      { label: '新客户', value: 9500, percentage: 20.8 },
      { label: '有风险客户', value: 5800, percentage: 12.7 },
      { label: '流失客户', value: 2728, percentage: 6.0 }
    ],
    segment_details: {
      '冠军客户': { avg_recency: 15, avg_frequency: 12, avg_monetary: 2850 },
      '忠诚客户': { avg_recency: 25, avg_frequency: 10, avg_monetary: 2150 },
      '潜力客户': { avg_recency: 20, avg_frequency: 6, avg_monetary: 1680 },
      '新客户': { avg_recency: 10, avg_frequency: 2, avg_monetary: 850 },
      '有风险客户': { avg_recency: 45, avg_frequency: 8, avg_monetary: 1450 },
      '流失客户': { avg_recency: 120, avg_frequency: 1, avg_monetary: 320 }
    },
    rfm_heatmap: [],
    summary: {
      total_segments: 6,
      covered_users: 45678,
      high_value_ratio: 32.5,
      segmentation_accuracy: 89.2
    }
  }
}

// 方法
const refreshData = async () => {
  await loadSegmentationData()
}

const createNewSegmentation = () => {
  ElMessage.info('新建分群功能开发中...')
}

const selectMethod = async (method) => {
  selectedMethod.value = method
  ElMessage.success(`已切换到${getMethodName(method)}`)
  // 重新加载数据
  await loadSegmentationData()
}



const exportSegmentation = () => {
  ElMessage.success('分群结果导出功能开发中...')
}

const viewSegmentDetail = (segment) => {
  currentSegment.value = segment
  showSegmentDetail.value = true
}

const createStrategy = (segment) => {
  ElMessage.info(`为${segment.name}创建营销策略功能开发中...`)
}

const handleSegmentChartClick = (params) => {
  ElMessage.info(`点击了分群: ${params.name}，用户数: ${params.value}`)
}

const handleValueChartClick = (params) => {
  ElMessage.info(`点击了分群: ${params.name}，平均价值: ¥${params.value}`)
}

const saveConfig = () => {
  showSegmentationConfig.value = false
  ElMessage.success('分群配置已保存')
}

// 生命周期
onMounted(() => {
  loadSegmentationData()
})
</script>

<style scoped>
.user-segmentation {
  padding: 0;
  background-color: transparent;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 分群概览 */
.segmentation-overview {
  margin-bottom: 24px;
}

.overview-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  overflow: hidden;
  position: relative;
}

.overview-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.overview-card:hover::before {
  opacity: 1;
}

.overview-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
}

.overview-icon {
  padding: 12px;
  border-radius: 12px;
  background: rgba(64, 158, 255, 0.1);
}

.overview-info h3 {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.overview-value {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.overview-desc {
  color: #999;
  font-size: 12px;
}

/* 分群方法 */
.segmentation-methods {
  margin-bottom: 24px;
}

.segmentation-methods .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.methods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.method-item {
  padding: 20px;
  border: 2px solid #f0f0f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.method-item:hover {
  border-color: #409EFF;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.method-item.active {
  border-color: #409EFF;
  background: rgba(64, 158, 255, 0.05);
}

.method-icon {
  margin-bottom: 16px;
}

.method-content h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.method-content p {
  margin: 0 0 12px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.method-features {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.method-status {
  position: absolute;
  top: 16px;
  right: 16px;
}

/* 分群结果 */
.segmentation-results {
  margin-bottom: 24px;
}

.segmentation-results .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.results-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.results-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 卡片视图 */
.card-view {
  padding: 20px 0;
}

.segments-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.segment-card {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.segment-card:hover {
  background: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.segment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.segment-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.segment-metrics {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.metric-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.metric-label {
  font-size: 12px;
  color: #666;
}

.segment-card .metric-value {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.segment-description {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
  margin-bottom: 16px;
}

.segment-actions {
  display: flex;
  justify-content: space-between;
}

/* 图表视图 */
.chart-view {
  padding: 20px 0;
}

.chart-container {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  height: 350px;
}

.chart-container h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  text-align: center;
}

/* 配置对话框 */
.weight-config {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.weight-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.weight-item span {
  width: 80px;
  font-size: 14px;
  color: #666;
}

/* 分群详情 */
.segment-detail {
  padding: 20px 0;
}

.feature-analysis {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.feature-item {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.feature-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.feature-name {
  font-weight: 500;
  color: #333;
}

.feature-value {
  font-size: 14px;
  color: #666;
}

.strategy-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.strategy-item {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.strategy-item h5 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.strategy-item p {
  margin: 0 0 12px 0;
  color: #666;
  line-height: 1.4;
}

.strategy-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .segmentation-overview .el-col {
    margin-bottom: 16px;
  }

  .methods-grid {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }

  .segments-grid {
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }

  .overview-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .results-header {
    flex-direction: column;
    gap: 12px;
  }

  .results-controls {
    justify-content: center;
    flex-wrap: wrap;
  }

  .methods-grid {
    grid-template-columns: 1fr;
  }

  .segments-grid {
    grid-template-columns: 1fr;
  }

  .segment-metrics {
    flex-direction: column;
    gap: 12px;
  }

  .metric-item {
    flex-direction: row;
    justify-content: space-between;
  }

  .chart-container {
    height: 250px;
  }

  .weight-item {
    flex-direction: column;
    gap: 8px;
  }

  .weight-item span {
    width: auto;
  }
}

@media (max-width: 480px) {
  .user-segmentation {
    padding: 0 16px;
  }

  .page-header {
    padding: 16px;
  }

  .overview-content {
    padding: 16px;
  }

  .overview-value {
    font-size: 20px;
  }

  .method-item {
    padding: 16px;
  }

  .segment-card {
    padding: 16px;
  }

  .chart-container {
    height: 200px;
    padding: 16px;
  }

  .header-actions {
    flex-direction: column;
    width: 100%;
  }

  .header-actions .el-button {
    width: 100%;
  }
}

/* 超小屏幕适配 */
@media (max-width: 360px) {
  .overview-content {
    padding: 12px;
  }

  .chart-container {
    height: 180px;
    padding: 12px;
  }

  .method-item {
    padding: 12px;
  }

  .segment-card {
    padding: 12px;
  }

  .results-controls {
    flex-direction: column;
    width: 100%;
  }

  .results-controls .el-select,
  .results-controls .el-button {
    width: 100% !important;
    margin-bottom: 8px;
  }
}
</style>
